package com.example.javademo;

import io.reactivex.rxjava3.core.Observable;
import io.reactivex.rxjava3.core.ObservableSource;
import io.reactivex.rxjava3.functions.BiFunction;
import io.reactivex.rxjava3.functions.Consumer;
import io.reactivex.rxjava3.functions.Function;
import io.reactivex.rxjava3.functions.Predicate;

public class RxJavaExample {
    public static void main(String[] args) {
        final String[] a = new String[]{"4", "0", "7", "i", "f", "w", "0", "9"};
        final Integer[] index = new Integer[]{5, 3, 9, 4, 8, 3, 1, 9, 2, 1, 7};

        Observable.just(index)    // 1. 传入 index 数组
                .flatMap(new Function<Integer[], ObservableSource<Integer>>() {
                    // flatMap 可将集合拆成一个个元素返回
                    @Override
                    public ObservableSource<Integer> apply(Integer[] integers) throws Throwable {
                        // 2. 调用 flatMap 方法将数组中的 Integer 元素一个个取出
                        return Observable.fromArray(integers);
                    }
                })
                .filter(new Predicate<Integer>() {
                    @Override
                    public boolean test(Integer i) throws Throwable {
                        // 3. 调用 filter 方法，将小于 a 数组长度的 元素 过滤出来
                        // 得到 5,3,4,3,1,2,1,7
                        return i < a.length;
                    }
                })
                .map(new Function<Integer, String>() {
                    // map 可将传入的参数类型，进行转换后输出
                    @Override
                    public String apply(Integer integer) throws Throwable {
                        // 4. 调用 map 方法，将得到的一串数字再依次作为 integer 参数输入 a[integer] 中
                        // 得到 "w","i","f","i","0","7","0","9"
                        return a[integer];
                    }
                })
                .reduce(new BiFunction<String, String, String>() {
                    @Override
                    public String apply(String s, String s2) throws Throwable {
                        // 5. 调用 reduce 方法，将 得到的字符串两两组合
                        // 得到 "wifi0709"
                        System.out.println("中间结果：s = " + s + "  s2 = " + s2);
                        return s + s2;
                    }
                })
                .subscribe(new Consumer<String>() {
                    @Override
                    public void accept(String s) throws Throwable {
                        System.out.println("最终结果：" + s);
                    }
                });
    }

}
